package com.atguigu.eduservice.service.impl;

import com.atguigu.eduservice.entity.EduCourse;
import com.atguigu.eduservice.entity.EduCourseDescription;
import com.atguigu.eduservice.entity.vo.CourseInfoVo;
import com.atguigu.eduservice.entity.vo.CoursePublishVo;
import com.atguigu.eduservice.mapper.EduCourseDescriptionMapper;
import com.atguigu.eduservice.mapper.EduCourseMapper;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduCourseService;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.eduservice.vo.CourseQueryVo;
import com.atguigu.eduservice.vo.frontVo.CourseFrontVo;
import com.atguigu.eduservice.vo.frontVo.CourseWebVo;
import com.atguigu.servicebase.exceptionHandler.MyException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-02-27
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    //因为往课程描述表里面插入数据，所以注入 courseDescriptionMapper 对象
    @Autowired
    private EduCourseDescriptionMapper courseDescriptionMapper;

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private EduChapterService eduChapterService;


    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }

    @Override
    public Map<String, Object> getConditionPage(Page<EduCourse> pageParam, CourseFrontVo courseFrontVo) {
        String title = null;
        String subjectId = null;
        String subjectParentId = null;
        String gmtCreateSort = null;
        String buyCountSort = null;
        String priceSort = null;
        String teacherId = null;

        if (courseFrontVo != null) {
            title = courseFrontVo.getTitle();
            subjectId = courseFrontVo.getSubjectId();
            subjectParentId = courseFrontVo.getSubjectParentId();
            gmtCreateSort = courseFrontVo.getGmtCreateSort();
            buyCountSort = courseFrontVo.getBuyCountSort();
            priceSort = courseFrontVo.getPriceSort();
            teacherId = courseFrontVo.getTeacherId();
        }


        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空拼接条件
        if (!StringUtils.isEmpty(subjectParentId)){//一级分类
            wrapper.eq("subject_parent_id",subjectParentId);
        }
        if (!StringUtils.isEmpty(subjectId)){//二级分类
            wrapper.eq("subject_id",subjectId);
        }
        if (!StringUtils.isEmpty(buyCountSort)){//关注度
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(priceSort)){//价格
            wrapper.orderByDesc("price");
        }
        if (!StringUtils.isEmpty(gmtCreateSort)){//最新，创建时间
            wrapper.orderByDesc("gmt_create");
        }


        baseMapper.selectPage(pageParam, wrapper);

        long total = pageParam.getTotal();//总记录数
        List<EduCourse> courseList = pageParam.getRecords();//数据集合
        long size = pageParam.getSize();//每页记录数
        long current = pageParam.getCurrent();//当前页
        long pages = pageParam.getPages();//总页数
        boolean hasPrevious = pageParam.hasPrevious();//是否有上一页
        boolean hasNext = pageParam.hasNext();//是否有下一页

        HashMap<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("list",courseList);
        map.put("size",size);
        map.put("current",current);
        map.put("pages",pages);
        map.put("hasPrevious",hasPrevious);
        map.put("hasNext",hasNext);

        return map;
    }

    @Override
    public void pageQuery(Page<EduCourse> pageParam, CourseQueryVo courseQueryVo) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();

        if (courseQueryVo != null) {
            String title = courseQueryVo.getTitle();
            String status = courseQueryVo.getStatus();
            String teacherId = courseQueryVo.getTeacherId();

            if (!StringUtils.isEmpty(title)) {
                queryWrapper.like("title", title);
            }
            if (!StringUtils.isEmpty(status)) {
                queryWrapper.eq("status", status);
            }
            if (!StringUtils.isEmpty(teacherId)) {
                queryWrapper.eq("teacher_id", teacherId);
            }
        }

        queryWrapper.orderByDesc("gmt_create");

        baseMapper.selectPage(pageParam, queryWrapper);
    }

    @Override
    public CoursePublishVo getpublishCourseInfo(String courseId) {
        CoursePublishVo coursePublishInfo = baseMapper.getCoursePublishInfo(courseId);
        return coursePublishInfo;
    }

    @Override
    public CourseInfoVo getCourseInfoByCourseId(String courseId) {
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        EduCourse eduCourse = baseMapper.selectById(courseId);
        BeanUtils.copyProperties(eduCourse, courseInfoVo);
        // 还要查询课程描述信息
        EduCourseDescription description = courseDescriptionMapper.selectById(courseId);
        courseInfoVo.setDescription(description.getDescription());

        return courseInfoVo;
    }


    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);

        int i = baseMapper.updateById(eduCourse);
        if (i == 0) {
            throw new MyException(20001, "修改课程信息失败");
        }
        // 还要修改课程描述信息
        EduCourseDescription description = new EduCourseDescription();
        description.setDescription(courseInfoVo.getDescription());
        description.setId(courseInfoVo.getId());
        courseDescriptionMapper.updateById(description);
    }

    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        // 因为课程表 和 课程描述表，是一对一的。所以，两个的id应该是一样的。
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);

        boolean save = this.save(eduCourse);
        if (!save) {
            throw new MyException(20001, "添加课程失败");
        }

        // 往课程描述表里面插入一条数据，id就是上面插入的课程id
        String id = eduCourse.getId();
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setId(id);
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescriptionMapper.insert(courseDescription);
        return id;
    }

    @Override
    @Transactional
    public boolean deleteCourse(String courseId) {
        // 小结
        eduVideoService.removeByCourseId(courseId);
        // 章节
        eduChapterService.removeByCourseId(courseId);
        // 课程描述
        courseDescriptionMapper.deleteById(courseId);
        // 课程
        int i = baseMapper.deleteById(courseId);
        if (i == 0) {
            throw new MyException(20001, "删除课程失败");
        }
        return true;
    }
}
